// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

/// 将阿拉伯数字转换为中文金额
/// 
/// # 参数
/// * `amount` - 要转换的金额（浮点数）
/// 
/// # 返回值
/// * `String` - 转换后的中文金额字符串
#[tauri::command]
fn convert_to_chinese_amount(amount: f64) -> String {
    // 中文数字映射
    let chinese_digits = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
    
    // 处理特殊情况
    if amount == 0.0 {
        return "零元整".to_string();
    }
    
    // 将金额转换为分为单位的整数，避免浮点数精度问题
    let cents = (amount * 100.0).round() as i64;
    
    if cents == 0 {
        return "零元整".to_string();
    }
    
    // 分离整数部分和小数部分
    let yuan = cents / 100;
    let jiao = (cents % 100) / 10;
    let fen = cents % 10;
    
    let mut result = String::new();
    
    // 处理整数部分（元）
    if yuan > 0 {
        result.push_str(&convert_integer_part(yuan, &chinese_digits));
        result.push_str("元");
    } else {
        result.push_str("零元");
    }
    
    // 处理角
    if jiao > 0 {
        result.push_str(chinese_digits[jiao as usize]);
        result.push_str("角");
    } else if fen > 0 && yuan > 0 {
        result.push_str("零");
    }
    
    // 处理分
    if fen > 0 {
        result.push_str(chinese_digits[fen as usize]);
        result.push_str("分");
    }
    
    // 如果没有角分，添加"整"
    if jiao == 0 && fen == 0 {
        result.push_str("整");
    }
    
    result
}

/// 转换整数部分（元以上的部分）
fn convert_integer_part(mut num: i64, chinese_digits: &[&str]) -> String {
    if num == 0 {
        return String::new();
    }
    
    let mut result = String::new();
    
    // 处理亿
    if num >= 100000000 {
        let yi = num / 100000000;
        result.push_str(&convert_section(yi, chinese_digits));
        result.push_str("亿");
        num %= 100000000;
        
        // 如果万位为0但有其他位，需要添加零
        if num > 0 && num < 10000000 {
            result.push_str("零");
        }
    }
    
    // 处理万
    if num >= 10000 {
        let wan = num / 10000;
        result.push_str(&convert_section(wan, chinese_digits));
        result.push_str("万");
        num %= 10000;
        
        // 如果个位段为0但有其他位，需要添加零
        if num > 0 && num < 1000 {
            result.push_str("零");
        }
    }
    
    // 处理个位段（千百十个）
    if num > 0 {
        result.push_str(&convert_section(num, chinese_digits));
    }
    
    result
}

/// 转换四位数以内的数字段
fn convert_section(mut num: i64, chinese_digits: &[&str]) -> String {
    if num == 0 {
        return String::new();
    }
    
    let mut result = String::new();
    let mut need_zero = false;
    
    // 千位
    if num >= 1000 {
        let qian = num / 1000;
        result.push_str(chinese_digits[qian as usize]);
        result.push_str("仟");
        num %= 1000;
        need_zero = true;
    }
    
    // 百位
    if num >= 100 {
        let bai = num / 100;
        if need_zero && result.len() > 0 {
            // 如果前面有数字且当前位不为0，不需要零
        }
        result.push_str(chinese_digits[bai as usize]);
        result.push_str("佰");
        num %= 100;
        need_zero = true;
    } else if need_zero && num > 0 {
        result.push_str("零");
        need_zero = false;
    }
    
    // 十位
    if num >= 10 {
        let shi = num / 10;
        if need_zero && result.len() > 0 {
            // 如果前面有数字且当前位不为0，不需要零
        }
        result.push_str(chinese_digits[shi as usize]);
        result.push_str("拾");
        num %= 10;
        need_zero = true;
    } else if need_zero && num > 0 {
        result.push_str("零");
    }
    
    // 个位
    if num > 0 {
        result.push_str(chinese_digits[num as usize]);
    }
    
    result
}

/// 根据系数计算转换后的金额
/// 
/// # 参数
/// * `amount` - 原始金额
/// * `coefficient` - 系数（百分数，如10表示10%）
/// 
/// # 返回值
/// * `String` - 转换后的中文金额
#[tauri::command]
fn convert_with_coefficient(amount: f64, coefficient: f64) -> String {
    let converted_amount = amount * coefficient / 100.0;
    convert_to_chinese_amount(converted_amount)
}

/// 批量转换多个系数的金额
/// 
/// # 参数
/// * `amount` - 原始金额
/// * `coefficients` - 系数数组
/// 
/// # 返回值
/// * `Vec<String>` - 转换后的中文金额数组
#[tauri::command]
fn batch_convert_with_coefficients(amount: f64, coefficients: Vec<f64>) -> Vec<String> {
    coefficients.iter()
        .map(|&coeff| convert_with_coefficient(amount, coeff))
        .collect()
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![
            greet,
            convert_to_chinese_amount,
            convert_with_coefficient,
            batch_convert_with_coefficients
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
